package com.english.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.english.entity.ClassAttendance;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.time.LocalDate;
import java.util.List;

/**
 * 班级签到记录Mapper接口
 *
 * @author wlq
 * @since 2025-08-08
 */
@Mapper
public interface ClassAttendanceMapper extends BaseMapper<ClassAttendance> {

    /**
     * 获取今日签到记录
     *
     * @param date 日期
     * @return 签到记录列表
     */
    @Select("SELECT ca.*, u.name as studentName, cc.class_name as className " +
            "FROM attendance ca " +
            "LEFT JOIN user u ON ca.student_id = u.id " +
            "LEFT JOIN course_class cc ON ca.class_id = cc.id " +
            "WHERE ca.attendance_date = #{date} " +
            "ORDER BY ca.sign_in_time DESC")
    List<ClassAttendance> getTodayAttendance(@Param("date") LocalDate date);

    /**
     * 获取学生的签到历史
     *
     * @param studentId 学生ID
     * @return 签到历史列表
     */
    @Select("SELECT ca.*, u.name as studentName, cc.class_name as className " +
            "FROM attendance ca " +
            "LEFT JOIN user u ON ca.student_id = u.id " +
            "LEFT JOIN course_class cc ON ca.class_id = cc.id " +
            "WHERE ca.student_id = #{studentId} " +
            "ORDER BY ca.attendance_date DESC, ca.sign_in_time DESC " +
            "LIMIT 50")
    List<ClassAttendance> getStudentAttendanceHistory(@Param("studentId") Long studentId);

    /**
     * 检查学生今日是否已签到
     *
     * @param studentId 学生ID
     * @param date 日期
     * @return 签到记录
     */
    @Select("SELECT * FROM attendance " +
            "WHERE student_id = #{studentId} AND attendance_date = #{date} " +
            "ORDER BY create_time DESC " +
            "LIMIT 1")
    ClassAttendance getTodayAttendanceByStudent(@Param("studentId") Long studentId, @Param("date") LocalDate date);

    /**
     * 更新签退时间
     *
     * @param id 签到记录ID
     * @param signOutTime 签退时间
     * @param status 状态
     * @return 更新行数
     */
    @Update("UPDATE attendance SET sign_out_time = #{signOutTime}, status = #{status}, update_time = NOW() " +
            "WHERE id = #{id}")
    int updateSignOut(@Param("id") Long id, @Param("signOutTime") String signOutTime, @Param("status") String status);
} 